axios.defaults.baseURL="http://localhost:8080"
//axios.defaults.baseURL="api.car.com"
Vue.prototype.$http=axios


//门户网站拦截
var stateHtml=["/list.html","/exam.html","/callback.html","/binder.html","/shoppingCar.html"]


function pareUrl(){
    let href = location.href;
    var strings = href.split("?")[1];
    var obj={}
    if(strings){
        var arry = strings.split("&");
        for (let i = 0; i <arry.length ; i++) {
            var arryElement = arry[i];
            var code = arryElement.split("=")[0];
            var value=arryElement.split("=")[1]
            obj[code]=value;
        }
    }
    return obj;
}


var flag=false;

var href = location.href;

if(href == 'http://127.0.0.1/'){
    location.href="/list.html"
    flag=true;
}else {
    for (let i = 0; i <stateHtml.length ; i++) {
        if(href.indexOf(stateHtml[i]) >-1){
            flag=true;
            break;
        }

    }

}


if(!flag){
    var token = localStorage.getItem("token");

    if(!token){
        alert("请登录后再访问")
        location.href="/list.html"

    }
}


// axios请求拦截器:添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
    config => {
        // 从localStorage中获取token
        let token = localStorage.getItem("token");

        // 如果token有值,我们就放到请求头里面
        if (token) {
            config.headers.token = token;
        }
        return config
    },
    error => {
        return Promise.reject(error)
    })
// 响应拦截器
axios.interceptors.response.use(function(response){
    //对返回的数据进行操作
    let result = response.data;  // response.data 就是后端返给我们的数据
    if(!result.success && result.message == "nologin"){ // 说明未登录,被拦截了,那么就要跳回到登陆页面
        location.href="/list.html"  // 跳转回登陆页面,让用户登陆
        alert("你还没有登陆，或者登陆过期")
    }else if(!result.success && result.message == "noPermission"){

        router.push({ path: '/403' });

    }
    else {

        return response
    }
},function(err){
    return Promise.reject(err)
})

